<?
include_once 'CoreModel.php';
Class ImportCustomerModel extends CoreModel {
	private $table;
	public function __construct() {
		$this -> table = "customer_data";
		parent::__construct();
	}

	public function insertConnectData($result) {
		/* $result is result from sap */
		//	print_r($result);
		//exit();
		// default log message
		$data_log['log_function'] = "ZSDRFC_CUSTOMER_DATA";
		$data_log['log_table'] = "CUSTOMER_DATA";
		$data_log['log_record'] = 0;
		$data_log['log_type'] = "INSERT";
		$data_log['log_status'] = "COMPLETED";
		$data_log['log_by_name'] = "Batch Job";
		$data_log['log_page'] = "adminpanel/importcustomer";

		$numRows = 0;
		// start begin trans
		$this -> db -> trans_begin();
		$this -> db -> query('delete from CUSTOMER_DATA');
		$this->db->query("SET NAMES tis620"); 
		$dataInsert = array();
		
		foreach ($result["CUSTOMER_DATA"] as $cus) {
			$data = array();

			$data['KUNNR'] = $cus["KUNNR"];
			$data['NAME'] = $cus["NAME"];
			$data['ADDRESS'] = $cus["ADDRESS"];
			$data['TELEPHONE'] = $cus["TELEPHONE"];
			$data['FAX'] = $cus["FAX"];
			$data['EMAIL'] = $cus["EMAIL"];
			$data['TAXID'] = $cus["TAXID"];
			$data['BRANCH'] = $cus["BRANCH"];
			$data['CUSTYP'] = $cus["CUSTYP"];
			$data['CUSTYP_TXT'] = $cus["CUSTYP_TXT"];
			$data['PLTYP'] = $cus["PLTYP"];
			$data['PLTYP_TXT'] = $cus["PLTYP_TXT"];
			$data['SALES_DIST'] = $cus["SALES_DIST"];
			$data['TZONE'] = $cus["TZONE"];
			$data['CUSGRP'] = $cus["CUSGRP"];
			$data['CUSGRP1'] = $cus["CUSGRP1"];
			$data['CUSGRP2'] = $cus["CUSGRP2"];
			$data['CUSGRP3'] = $cus["CUSGRP3"];
			$data['CUSGRP4'] = $cus["CUSGRP4"];
			$data['CUSGRP5'] = $cus["CUSGRP5"];
			$data['CREDIT_LIMIT'] = $this->convertValue($cus["CREDIT_LIMIT"]);
			$data['CREDIT_USED'] = $this->convertValue($cus["CREDIT_USED"]);
			$data['CREDIT_LEFT'] = $this->convertValue($cus["CREDIT_LEFT"]);
			$data['SALES_NO'] = $cus["SALES_NO"];
			$data['SALES_NAME'] = $cus["SALES_NAME"];

			$dataInsert[] = $data;
		}

		// insert into CUSTOMER_DATA;
		$this -> db -> insert_batch($this -> table, $dataInsert);

		if ($this -> db -> trans_status() === FALSE) {
			// if error on tranaction
			$this -> db -> trans_rollback();
				
			// insert log  table & page
			$this->insertLogFailed('ZSDRFC_CUSTOMER_DATA','CUSTOMER_DATA', 'adminpanel/importcustomer');
			
			return array("flag" => false, "message" => "error on transfer");
		} else {
			// when complete
			$this -> db -> trans_commit();
			$this->insertLogComplete('ZSDRFC_CUSTOMER_DATA','CUSTOMER_DATA', count($dataInsert), 'adminpanel/importcustomer');
			//$this->insertLogComplete('SALES_DATA', count($result["SALES_DATA"]));		
			//return array("flag" => true, "customer_row" => count($dataInsert), "sale_row" => count($result["SALES_DATA"]));	
			//return ค่าไป controller
			return array("flag" => true, "connect_row" => count($dataInsert));
		}
	}

}
?>